# -*- coding: utf-8 -*-
# @Time : 2020/8/14 15:42
# @Author : yongf
# @File : Db.py
# @Software: PyCharm

from utils.Common import *
import mysql.connector
import database



class Db:
    def __init__(self):
        localhost = database.host
        user = database.user
        password = database.password
        dbname = database.dbname
        try:
            self.db = mysql.connector.connect(
                host=localhost,
                user=user,
                password=password,
                database=dbname,
            )
        except Exception as e:
            logging.error(e)
            logging.error("连接数据库失败... [lost=%s][dbname=%s]" % (localhost, dbname))

    def select(self, sql):
        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            return cursor.fetchall()
        except:
            logging.error("Error: unable to fecth data")
            return []

    # 返回查询结果的第一条数据
    def selectOne(self, sql):
        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            return cursor.fetchone()
        except:
            logging.error("Error: unable to fecth data")
            return []

    def insert(self, sql):
        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            self.db.commit()
            return True
        except:
            self.db.rollback()
            return False

    def delete(self, sql):
        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            self.db.commit()
            return True
        except:
            return False

    def close(self):
        self.db.close()
